//
//  LYQNetworkManager +  extension.swift
//  SwiftWeibo
//
//  Created by 刘英群 on 2017/1/4.
//  Copyright © 2017年 刘英群. All rights reserved.
//

//MARK: 封装新浪微博请求方法
import Foundation

extension LYQNetworkManager {
    
    /// 加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id:若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id:若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调(微博字典数组，是否成功)
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion : @escaping ([[String: Any]]?, Bool)->()) {
        
        // 用网络工具加载微博数据
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
//        let urlString = "https://api.weibo.com/2/statuses/public_timeline.json"

        //
        let params = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        
        tokenRequest(URLString: urlString, parameters: params) { (response, isSuccess) in
            
            // 从json中获取statuses字典数组
            // 如果as？失败, result = nil，分开解 一步一步解开
            let result = response as? [String : Any]
            let json = result?["statuses"] as? [[String: Any]]
            completion(json, isSuccess)
        }
    }
    
    //返回微博的未读数量，定时刷新，不需要提示是否失败
    func unreadCount(completion: @escaping(_ count: Int) -> ()) {
        
        guard let uid = userAccount.uid else {
            
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess ) in
            
            let dict = json as? [String: Any]
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
    }
}

//MARK: 加载用户信息
extension LYQNetworkManager {
    
    //加载当前用户信息 - 用户登陆后立即执行
    func loadUserInfo(completion: @escaping (_ dict: [String: Any]) -> ()){
        
        guard let uid = userAccount.uid else {
            
            return
        }
        
       let urlString = "https://api.weibo.com/2/users/show.json"
       let params = ["uid": uid]
        
        //网络请求
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            
            completion((json as? [String: Any]) ?? [:])
        }
    }
}

//MARK: OAuth相关方法
//网络异步到底要返回什么，需要什么返回什么
extension LYQNetworkManager {
    
    
    /// 加载 AccessToken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调[是否成功]
    func loadAccessToken(code: String, completion:@escaping (_ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": LYQAppKey,
                      "client_secret": LYQAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": LYQRedirectURI,]
        
        //发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            
            // 如果请求失败，对用户账户数据不会有任何影响
            // 直接用字典设置 userAccount的属性
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
            print("用户数据--->>>>>>\(self.userAccount)")
            
            //保存模型
            self.userAccount.saveAccount()
            
            //加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                
                print(dict)
                //使用用户信息字典设置用户账户信息（昵称和头像地址）
                self.userAccount.yy_modelSet(with: dict)
                
                //保存模型 
                self.userAccount.saveAccount()
                
                print(self.userAccount)
                
                //用户信息加载完成再，完成回调
                completion(isSuccess)
            })
        }
    }
}
